package ysf.com.simplediffculty;

import java.util.Stack;

/**
 *  input:'()'   output:true
 *  input:'(){}' output:true
 *  input:'(){}[{]'
 *  判断括号是否成对出现
 *
 * @author ysf
 * @date 2021/7/12 22:31
 */
public class TwentiethDemos {

    public static void main(String[] args) {
        String s = "(){{";
        boolean valid = isValid(s);
        System.out.println(valid);
    }

    public static boolean isValid(String s) {

        Stack<Character> brackets = new Stack<Character>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
                case '(':
                case '[':
                case '{':
                    brackets.push(c);
                    break;
                case ')':
                    if (!brackets.empty()) {
                        if (brackets.peek() == '(') {
                            brackets.pop();
                        } else {
                            return false;
                        }
                    } else {
                        return false;
                    }
                    break;
                case ']':
                    if (!brackets.empty()) {
                        if (brackets.peek() == '[') {
                            brackets.pop();
                        } else {
                            return false;
                        }
                    } else {
                        return false;
                    }
                    break;
                case '}':
                    if (!brackets.empty()) {
                        if (brackets.peek() == '{') {
                            brackets.pop();
                        } else {
                            return false;
                        }
                    } else {
                        return false;
                    }
            }
        }
        return brackets.empty();
    }

}
